package com.reason.register.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import com.reason.common.enums.RedisMessageStatusCode;
import com.reason.common.pojo.Result;
import com.reason.common.pojo.StatusCode;
import com.reason.register.service.RegisterService;
import com.reason.user.pojo.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;


/**
 * @author tang wei
 * @version 1.0
 * @date 2020/6/30 10:15
 */
@RestController
@RequestMapping("/register")
public class RegisterController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RegisterService registerService;

    /**
     * 注册信息验证，并添加到数据库
     * @param customer 客户封装类
     * @return  注册是否成功
     */
    @PostMapping("/addCustomer/{code}")
    public  Result addCustomer(@RequestBody Customer customer,@PathVariable String code){
        //1、判断用户输入的短信验证码是否正确，或者过期
        //1.1从redis中取出存储的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(String.valueOf(customer.getPhone()) + RedisMessageStatusCode.SENDTYPE_REGISTER);
        if(redisCode==null||redisCode.equals("")){
            return new Result(false,StatusCode.ERROR,"验证码已经过期，请重新发送");
        }
        //1.2判断输入的验证码是否等于redis中取出的验证吗，若是错误，则返回信息
        if(!redisCode.equals(code)){
            return new Result(false,StatusCode.ERROR,"验证码输入错误，请重新发送");
        }
        //2、判断用户当前注册的手机号是否已经注册
        Long phone = customer.getPhone();
        //2.1通过用户输入的手机号查找数据库，如果查找的数据为空，则添加数据
        Customer customer1=registerService.findCustomerByPhone(phone);
        //2.2已经注册，给出提示
        if(customer1!=null){
            return new Result(false,StatusCode.ERROR,"此手机号已经注册，请重新输入手机号");
        }
        //3、用户未注册则添加到数据库中
        //对输入的密码进行加密
        String gensalt = BCrypt.gensalt();
        customer.setPassword(BCrypt.hashpw("123456",gensalt));
        //设置用户当前的身份是最普通身份
        customer.setMember(0);
        //设置用户的id
        customer.setId(IdWorker.getId());
        //将用户信息存入数据库
        registerService.addCustomer(customer);
        return  new Result(true,StatusCode.OK,"用户注册成功");
    }
}
